package database.rescue;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

import database.PrepareFiles;

public class GetProfileDatabase {
	private String login;
	private Properties profile;
	private File file;
	
	public GetProfileDatabase(String login) throws Exception {
		this.login = login;
		file = new File(getPath());
	}
	
	public void setLogin(String login) throws Exception {
		this.login = login;
		file = new File(getPath());
	}
	
	public Properties getProfile() throws Exception {
		if(!file.exists()) {
			throw new Exception("Login inexistente");
		}
		return getProfileFromFile(file);
		
	}
	
	public void remove() {
		file.delete();
		
	}
	
	public void clear() {
		file = null;
		login = null;
		profile = null;
	}
	
	private String getPath() throws Exception {
		if(login == null) {
			throw new Exception("Login Invalido.");
		}
		return "Database/"+login+"/"+login+".xml";
	}
	
	private Properties getProfileFromFile(File file) throws IOException {
		profile = new Properties();
		try {
			
			PrepareFiles.prepareFile(file.getAbsolutePath(), "");
			FileInputStream in = new FileInputStream(file.getAbsolutePath());
			profile.loadFromXML(in);
			in.close();
			
		} catch (InvalidPropertiesFormatException e) {
			this.login = null;
			throw new InvalidPropertiesFormatException("The " + login
					+ ".xml is corupted.");
		}
		
		return profile;
	}
}
